﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Mani.Common.Security;
using RastinArgham.CRM.Business;
using Mani.Common;

namespace RastinArgham.CRM.Web
{
    public partial class list_cities : System.Web.UI.Page
    {
        public ISecurityManager securityManager { get; set; }
        public CRMRepository crmRepository { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (securityManager == null)
            {
                securityManager = new SecurityManager();
                securityManager.authProvider = new WebAuthorizationProvider();
            }

            if (crmRepository == null)
                crmRepository = new CRMRepository();


            if (!securityManager.IsActionPermitted("provinces"))
                Response.Redirect("~/access_denied.aspx");

            if (!Page.IsPostBack)
            {
                LoadProvinces();
                LoadCities();
            }
        }

        private void LoadCities()
        {
            if (ddlProvinces.SelectedValue == "-1")
            {
                divCityData.Visible = false;
                return;
            }

            divCityData.Visible = true;
            int selectedProvince = Convert.ToInt32(ddlProvinces.SelectedValue);
            gvCities.DataSource = crmRepository.GetCities(selectedProvince);
            gvCities.DataBind();
        }

        private void LoadProvinces()
        {
            ddlProvinces.DataSource = crmRepository.GetProvinces();
            ddlProvinces.DataBind();
        }

        protected void ddlProvinces_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadCities();
        }

        protected void gvCities_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            int cityId = Convert.ToInt32(gvCities.DataKeys[e.RowIndex].Value);
            crmRepository.DeleteCity(cityId);
            crmRepository.Save();
            LoadCities();
        }

        protected void gvCities_RowCreated(object sender, GridViewRowEventArgs e)
        {
            UIHelper.GridDeleteConfirm(e.Row);
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            City c = new City();
            c.CityName = txtCityName.Text;
            c.Province = crmRepository.GetProvinceById(Convert.ToInt32(ddlProvinces.SelectedValue));
            c.OperatorId = securityManager.authProvider.GetCurrentUser().UserId;
            crmRepository.AddCity(c);
            crmRepository.Save();

            UIHelper.ClientAlert(this, "تغییرات با موفقیت ذخیره شد");
            txtCityName.Text = String.Empty;
            LoadCities();
        }
    }
}   